package com.yufeng.collaboration.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yufeng.collaboration.entity.Document;
import com.yufeng.collaboration.mapper.DocumentMapper;
import com.yufeng.collaboration.mapper.DocumentUserMapper;
import com.yufeng.collaboration.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, Document> implements DocumentService {

    @Autowired
    private RedisTemplate<String, Document> redisTemplate;

    @Autowired
    private DocumentUserMapper documentUserMapper;

    @Override
    public void updateDocument(Document document) {
        try {
            // 更新数据库
            baseMapper.updateById(document);
            // 更新缓存
            redisTemplate.opsForValue().set("document:" + document.getId(), document, 60, TimeUnit.MINUTES);
        } catch (Exception e) {
            // 可添加更详细的日志记录
            e.printStackTrace();
        }
    }

    @Override
    public List<Document> getDocumentsByUserId(Long userId) {
        try {
            // 根据用户 ID 查询关联的文档 ID
            List<Long> documentIds = documentUserMapper.selectDocumentIdsByUserId(userId);
            // 根据文档 ID 查询文档列表
            return baseMapper.selectBatchIds(documentIds);
        } catch (Exception e) {
            // 可添加更详细的日志记录
            e.printStackTrace();
            return java.util.Collections.emptyList();
        }
    }
}    